import {
  getBreadCrumbList,
  getHomeRoute,
  getMenuByRouter,
  getNextRoute,
  getRouteTitleHandled,
  getTagNavListFromLocalstorage,
  localRead,
  localSave,
  routeEqual,
  routeHasExist,
  setTagNavListInLocalstorage,
} from '@/libs/util'
import beforeClose from '@/router/before-close'
//import { saveErrorLogger } from '@/modules/module-login/api/login'
import router from '@/router'
import routers from '@/router/routers'
import config from '@/config'
import {defineStore} from "pinia";
import {computed, ref} from "vue";

const { homeName } = config


export const useAppStore = defineStore('app', () => {
  const breadCrumbList = ref([])
  const tagNavList = ref([])
  const homeRoute = getHomeRoute(routers, homeName)
  let local = localRead('local')
  const errorList = []
  let hasReadErrorPage = false

  const _closePage = (route) => {
    const nextRoute = getNextRoute(tagNavList.value, route)
    tagNavList.value = tagNavList.value.filter((item) => {
      return !routeEqual(item, route)
    })
    router.push(nextRoute)
  }

  function setBreadCrumb(route) {
    breadCrumbList.value = getBreadCrumbList(route, homeRoute)
  }

  function setTagNavList(list) {
    let tagList = []
    if (list) {
      tagList = [...list]
    } else tagList = getTagNavListFromLocalstorage() || []
    if (tagList[0] && tagList[0].name !== homeName) tagList.shift()
    let homeTagIndex = tagList.findIndex((item) => item.name === homeName)
    if (homeTagIndex > 0) {
      let homeTag = tagList.splice(homeTagIndex, 1)[0]
      tagList.unshift(homeTag)
    }
    tagNavList.value = tagList
    setTagNavListInLocalstorage([...tagList])
  }

  function closeTag(route) {
    let tag = tagNavList.value.filter((item) => routeEqual(item, route))
    route = tag[0] ? tag[0] : null
    if (!route) return
    if (
        route.meta &&
        route.meta.beforeCloseName &&
        route.meta.beforeCloseName in beforeClose
    ) {
      new Promise(beforeClose[route.meta.beforeCloseName]).then((close) => {
        if (close) {
          _closePage(route)
        }
      })
    } else {
      _closePage(route)
    }
  }

  function addTag({route, type = 'unshift'}) {
    let router = getRouteTitleHandled(route)
    if (!routeHasExist(tagNavList.value, router)) {
      if (type === 'push') tagNavList.value.push(router)
      else {
        if (router.name === homeName) tagNavList.value.unshift(router)
        else tagNavList.value.splice(1, 0, router)
      }
      setTagNavListInLocalstorage([...tagNavList.value])
    }
  }

  return {
    breadCrumbList,
    tagNavList,
    homeRoute,
    local,
    errorList,
    hasReadErrorPage,
    setBreadCrumb,
    setTagNavList,
    closeTag,
    addTag
  }
})